package com.vectz.autogen.action;

import java.io.IOException;
import java.util.ArrayList;

import com.vectz.autogen.model.Entity;
import com.vectz.autogen.model.EntityOverview;
import com.vectz.autogen.util.Constant;
import com.vectz.autogen.util.Log;
import com.vectz.autogen.util.Util;
/**
 * @author ai-t.vn
 *
 */
public class IDAOCodegenAction {
	ArrayList<Entity> listField=null;
	EntityOverview table = null;
	String outputFolder = "";
	public IDAOCodegenAction(ArrayList<Entity> listField, EntityOverview table, String outputFolder) {
		this.listField = listField;
		this.table = table;
		this.outputFolder = outputFolder;
		genernateIDaoFile();
	}
	/*
	 * Generate DAO interface file
	 */
	public void genernateIDaoFile() {
		try {
			String iDAOContent = "";
			
			String tmplIDaoContent = Util.readTextFileContent(Util
					.getTmplPath("dao","IDao-File.txt"));
			
			// add content path
			iDAOContent = genernateIDaoFile(table, tmplIDaoContent);
			String fileLocation = new StringBuffer().append(outputFolder)
			.append(System.getProperty("file.separator"))
			.append("src")
			.append(System.getProperty("file.separator"))
			.append("dao")
			.append(System.getProperty("file.separator"))
			.append("local")
			.append(System.getProperty("file.separator"))
			.append("I")
			.append(table.getName())
			.append("Dao.java").toString();
			
			Util.writeJavaFile(fileLocation, iDAOContent);
			Log.log("Finish generate IDao file to: "+fileLocation);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	/*
	 * Generate header file
	 */
	public String genernateIDaoFile(EntityOverview table, String tmpContent) {
		if (Util.isEmpty(tmpContent))
			return "";
		//replace package name
		tmpContent = tmpContent.replaceAll("xxxxIDaoPackageName", table
				.getPackageName());
		//replace DAO class name
		tmpContent = tmpContent
				.replaceAll("xxxxClassName", table.getName());
		
		tmpContent = tmpContent.replaceAll("xxxxName",  new StringBuffer().append(table.getPackageName())
					.append(".model.")
					.append(table.getName()).toString());
		
		tmpContent = tmpContent.replaceAll("xxxxIdType", Util.getPKType(listField));
		
		return tmpContent;
	}
}
